package com.xnew.menu.controller;

import com.alibaba.fastjson.JSONObject;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.exception.CustomException;
import com.xnew.menu.bean.Menu;
import com.xnew.menu.service.MenuService;
import com.xnew.utils.ResponseUtil;
import com.xnew.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sysMenu-api")
public class MenuController {
	
	private final MenuService menuService;

    @Autowired
    public MenuController(MenuService menuService) {
        this.menuService = menuService;
    }
	
	@ResponseBody
	@RequestMapping("/querySysMenuList")
	public String querySysMenuList(HttpServletRequest request){
		try{
//			SysUserInfo user = (SysUserInfo)request.getSession().getAttribute(Constant.LOGIN_USER);
			SysUserInfo user = UserUtil.getUserInfo(request);
			return ResponseUtil.responseMsg(menuService.createMenu(user.getLoginName(), user.getUserInfoNo()));
		}catch(Exception e){
			e.printStackTrace();
			return ResponseUtil.responseMsg("9999", "操作失败");
		}
	}


	@ResponseBody
	@RequestMapping("/getSysRemindMenu")
	public String getSysRemindMenu(HttpServletRequest request){
		try{
			SysUserInfo user = UserUtil.getUserInfo(request);
			HashMap<String, List<Menu>> resultMap = menuService.getSysRemindMenu(user.getLoginName(), user.getUserInfoNo());
			return ResponseUtil.responseMsg(resultMap);
		}catch(Exception e){
			e.printStackTrace();
			throw new CustomException();
		}
	}
	
	@ResponseBody
	@RequestMapping("/addOrUpdateMenu")
	public String addOrUpdateMenu(@RequestBody JSONObject json){
		try{
			menuService.addOrUpdateMenu(JSONObject.toJavaObject(json, Menu.class));
			return ResponseUtil.responseMsg("0001", "操作成功");
		}catch(Exception e){
			e.printStackTrace();
			return ResponseUtil.responseMsg("9999", "操作失败");
		}
	}
	
	@ResponseBody
	@RequestMapping("/querySysMenuById")
	public String querySysMenuById(@RequestBody JSONObject json){
		try{
			Menu menu = menuService.querySysMenuById(json.getString("id"));
			return ResponseUtil.responseMsg(menu);
		}catch(Exception e){
			e.printStackTrace();
			return ResponseUtil.responseMsg("9999", "操作失败");
		}
	}
	
	@ResponseBody
	@RequestMapping("/deleteById")
	public String deleteById(@RequestBody JSONObject json){
		try{
			menuService.deleteById(json.getString("id"));
			return ResponseUtil.responseMsg("0001", "操作成功");
		}catch(Exception e){
			e.printStackTrace();
			return ResponseUtil.responseMsg("9999", "操作失败");
		}
	}
}
